package com.tj.collection.task;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.tj.collection.db.dao.ClAllocationDetailDao;
import com.tj.collection.db.dao.ClReceiverDao;
import com.tj.collection.db.entity.ClAllocationDetailEntity;
import com.tj.collection.db.entity.business.WrongPaidStatusCollectionOrderVo;
import com.tj.collection.enums.AllocationStatusEnum;
import com.tj.collection.utils.ConfigUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2019-09-16
 * Time: 14:11
 * <p>
 * 修复分单早点的已还未还为题
 */
@Service
public class FixWrongAllocation implements SimpleJob {

    private static final Log LOGGER = LogFactory.getLog(FixWrongAllocation.class);

    @Autowired
    private ClReceiverDao receiverDao;

    @Autowired
    private ClAllocationDetailDao allocationDetailDao;


    @Autowired
    private ConfigUtil configUtil;

    @Override
    public void execute(ShardingContext shardingContext) {
        run();
    }

    public void run() {
        if (!configUtil.getCollectionFixJobSwitch()) {
            LOGGER.info("催收状态修复任务暂停");
            return;
        }

        List<WrongPaidStatusCollectionOrderVo> wrongPaidStatusCollectionOrders = receiverDao.getWrongPaidStatusCollectionOrders();
        if (CollectionUtils.isEmpty(wrongPaidStatusCollectionOrders)) {
            LOGGER.info("== FixWrongAllocation 获取当前已结清的订单为空 ==,size:{}", wrongPaidStatusCollectionOrders.size());
            return;
        }

        LOGGER.warn("== FixWrongAllocation 获取当前已结清的订单 ==,size:{}", wrongPaidStatusCollectionOrders.size());

        List<String> collectionNos = new ArrayList<>();
        wrongPaidStatusCollectionOrders.forEach(re -> {
            //加时间条件 避免job比trade推催收还快
            Date date = DateUtils.addMinutes(new Date(), -30);
            if (re.getGmtModified().getTime() < date.getTime()) {
                collectionNos.add(re.getCollectionNo());
            }
        });
        if (CollectionUtils.isNotEmpty(collectionNos)) {
            receiverDao.updateStatusByCollectionNos(collectionNos, 2);
            LOGGER.info("催收状态修复任务处理成功,collectionNos:{}", collectionNos.toString());
        }
        LOGGER.info("催收状态修复任务完成,collectionNos:{}", collectionNos.toString());
    }

    private void updateBatchData(String collectionNo, Date payOffDate) {

        if (payOffDate == null) {
            LOGGER.info("== FixWrongAllocation collectionNo的还清时间为空,不做处理 ==,collectionNo:{}", collectionNo);
            return;
        }

        List<ClAllocationDetailEntity> listByCollectionNo = allocationDetailDao.getListByCollectionNo(collectionNo);
        if (CollectionUtils.isEmpty(listByCollectionNo)) {
            LOGGER.error("== FixWrongAllocation 找不到collectionNo ==,collectionNo:{}", collectionNo);
            return;
        }

        List<ClAllocationDetailEntity> currentAllocationDetailList = new ArrayList<>();
        List<ClAllocationDetailEntity> beforeAllocationDetailList = new ArrayList<>();
        List<ClAllocationDetailEntity> afterAllocationDetailList = new ArrayList<>();
        listByCollectionNo.forEach(dt -> {
            Integer diffDays = DateUtil.diffDate(dt.getGmtCreate(), payOffDate);
            if (diffDays == 0) {
                currentAllocationDetailList.add(dt);
            } else if (diffDays < 0) {
                beforeAllocationDetailList.add(dt);
            } else {
                afterAllocationDetailList.add(dt);
            }
        });

        //整理一个list用户存放所有需要更改的detail记录
        List<ClAllocationDetailEntity> allTheRecordsNeedUpdate = new ArrayList<>();

        //处理当天的记录
        if (CollectionUtils.isEmpty(currentAllocationDetailList)) {
            LOGGER.error("== FixWrongAllocation 找不到对应当天的分单记录 ==,collectionNo:{},dt:{}", collectionNo, payOffDate);
        } else {
            //排序
            currentAllocationDetailList.sort(Comparator.comparing(ClAllocationDetailEntity::getId));
            LOGGER.info("== FixWrongAllocation 找到对应当天的分担记录 ==,collectionNo:{},size:{}", collectionNo, currentAllocationDetailList.size());


            //同一天有多条记录，那么最后一条置为已还款的记录，其余的置为流转状态
            int size = currentAllocationDetailList.size();
            if (size == 1) {
                ClAllocationDetailEntity allocationDetailEntity = currentAllocationDetailList.get(0);
                allocationDetailEntity.setStatus(AllocationStatusEnum.COLLECTION_END.getStatus());
                allTheRecordsNeedUpdate.add(allocationDetailEntity);
            } else {
                for (int i = 0; i < size; i++) {
                    ClAllocationDetailEntity allocationDetailEntity = currentAllocationDetailList.get(i);
                    if (i == size - 1) {
                        allocationDetailEntity.setStatus(AllocationStatusEnum.COLLECTION_END.getStatus());
                    } else {
                        allocationDetailEntity.setStatus(AllocationStatusEnum.INVALID.getStatus());
                    }

                    allTheRecordsNeedUpdate.add(allocationDetailEntity);
                }
            }
        }


        //如果还清日之后还被分单了，那么这些分单的数据置为失效
        if (CollectionUtils.isNotEmpty(afterAllocationDetailList)) {
            LOGGER.info("== FixWrongAllocation 找到对应当天之后的分担记录 ==,collectionNo:{},size:{}", collectionNo, afterAllocationDetailList.size());
            afterAllocationDetailList.forEach(dt -> {
                LOGGER.info("== FixWrongAllocation 找到对应当天之后的分担记录 ==,collectionNo:{},allocationNo:{}", collectionNo, dt.getAllocationNo());
                dt.setStatus(AllocationStatusEnum.INVALID.getStatus());
                allTheRecordsNeedUpdate.add(dt);
            });
        }

        if (CollectionUtils.isNotEmpty(beforeAllocationDetailList)) {
            LOGGER.info("== FixWrongAllocation 找到对应当天之前的分担记录 ==,collectionNo:{},size:{}", collectionNo, beforeAllocationDetailList.size());
            beforeAllocationDetailList.forEach(dt -> {
                LOGGER.info("== FixWrongAllocation 找到对应当天之前的分担记录 ==,collectionNo:{},allocationNo:{}", collectionNo, dt.getAllocationNo());
                if (dt.getStatus().equals(AllocationStatusEnum.COLLECTION_END.getStatus()) || dt.getStatus().equals(AllocationStatusEnum.INVALID.getStatus())) {
                    dt.setStatus(AllocationStatusEnum.COLLECTING.getStatus());
                    allTheRecordsNeedUpdate.add(dt);
                }

                //修复一个当时的bug  16号的gmt_modify 把这个时间是transfer状态的数据更新为处理中
//                Date bugDate = TimeUtils.getDateByStr("2019-09-16 17:58:40", "yyyy-MM-dd HH:mm:ss");
//                if (dt.getStatus().equals(AllocationStatusEnum.TRANSFERRED.getStatus()) && DateUtil.diffDate(bugDate, dt.getGmtModified()) == 0) {
//                    dt.setStatus(AllocationStatusEnum.COLLECTING.getStatus());
//                    allTheRecordsNeedUpdate.add(dt);
//                }
            });
        }

        if (CollectionUtils.isNotEmpty(allTheRecordsNeedUpdate)) {
            LOGGER.info("== FixWrongAllocation 需要更新的详细 ==,collectionNo:{},size:{}", collectionNo, allTheRecordsNeedUpdate.size());
            if (!configUtil.isFixWrongAllocationStrageSwitchOpen()) {
                LOGGER.info("== FixWrongAllocation 需要更新的详细，更新开关未打开 ==,collectionNo:{},size:{}", collectionNo, allTheRecordsNeedUpdate.size());
                return;
            }

            allTheRecordsNeedUpdate.forEach(dt -> {
                allocationDetailDao.updateByPrimaryKey(dt);
            });
        }

    }
}
